﻿using UnityEngine;
using System.Collections;
using Assets.components;
using FrenzyIsland.UI;
using Game.Scripts.Managers;
using Assets.entities;

[RequireComponent(typeof(BuildingManager))]
public class TerrainFirerController : MonoBehaviour {

    public VoxelWorld worldObject;
    public AstarPath pathfindObject;

    private bool isResponsive = true;
    private int currentPrototypeIndex = 0;

    public bool IsResponsive { 
        get {
            return this.isResponsive;
        } 
        
        set{
            this.isResponsive = value;
        } 
    }


	void Update () {
        if (this.IsResponsive && this.worldObject!=null && this.pathfindObject!=null) { 
            if (Input.GetMouseButtonDown(0) && Input.GetKey(KeyCode.LeftControl) ) {
                RaycastHit hit;
                Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

                if (Physics.Raycast(ray, out hit)) {
                    
                    Vector3 voxelHitPosition = this.getPositionFromHit(hit, false);
                    float x = voxelHitPosition.x;
                    float y = voxelHitPosition.y;
                    float z = voxelHitPosition.z;
                    
                    BuildingManager manager = this.GetComponent<BuildingManager>();
                    //BuildingPrototype prototype = manager.getPrototypeByIndex(this.currentPrototypeIndex);
                    BuildingPrototype prototype = manager.getPrototypeByName("bar");
                    Building building = prototype.instantiateBuildingAt(x, y, z);

                    this.currentPrototypeIndex = (this.currentPrototypeIndex + 1) % manager.prototypeCount;

                }
            }
        }
	}
    
    private float moveWithinVoxel(float pos, float norm, bool adjacent) {
        if (pos - (int)pos == 0.5f || pos - (int)pos == -0.5f) {
            if (adjacent) {
                pos += (norm / 2);
            } else {
                pos -= (norm / 2);
            }
        }

        return (float)pos;
    }
    
    private Vector3 getPositionFromHit(RaycastHit hit, bool adjacent) {
        float x = this.moveWithinVoxel(hit.point.x, hit.normal.x, adjacent);
        float y = this.moveWithinVoxel(hit.point.y, hit.normal.y, adjacent);
        float z = this.moveWithinVoxel(hit.point.z, hit.normal.z, adjacent);

        return new Vector3(Mathf.Round(x), Mathf.Round(y), Mathf.Round(z));
    }

}
